/**
 * Copyright &copy; 2012-2015 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.zouqone.smc.modules.sys.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zouqone.smc.common.config.Global;
import com.zouqone.smc.common.persistence.Page;
import com.zouqone.smc.common.web.BaseController;
import com.zouqone.smc.common.utils.ActionHelp;
import com.zouqone.smc.common.utils.StringUtils;
import com.zouqone.smc.common.utils.vo.TreeVo;
import com.zouqone.smc.modules.sys.entity.Dict;
import com.zouqone.smc.modules.sys.entity.Dictitem;
import com.zouqone.smc.modules.sys.service.DictService;
import com.zouqone.smc.modules.sys.service.DictitemService;

/**
 * 字典项管理Controller
 * @author zouqh
 * @version 2015-05-26
 */
@SuppressWarnings("unused")
@Controller
@RequestMapping(value = "${adminPath}/sys/dictitem")
public class DictitemController extends BaseController {

	@Autowired
	private DictitemService dictitemService;
	
	@ModelAttribute
	public Dictitem get(@RequestParam(required=false) String id) {
		Dictitem entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = dictitemService.get(id);
		}
		if (entity == null){
			entity = new Dictitem();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:dictitem:view")
	@RequestMapping(value = {"index"})
	public String indexPage(Dictitem dictitem, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "modules/sys/dict/dictitemIndex";
	}
	
	@RequiresPermissions("sys:dictitem:view")
	@RequestMapping(value = {"list", ""})
	public String list(Dictitem dictitem, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Dictitem> page = dictitemService.findPage(new Page<Dictitem>(request, response), dictitem); 
		model.addAttribute("page", page);
		return "modules/sys/dict/dictitemList";
	}

	@RequiresPermissions("sys:dictitem:view")
	@RequestMapping(value = "form")
	public String form(Dictitem dictitem, Model model) {
		model.addAttribute("dictitem", dictitem);
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("opt",request.getParameter("opt"));
		return "modules/sys/dict/dictitemForm";
	}

	@RequiresPermissions("sys:dictitem:edit")
	@RequestMapping(value = "save")
	public String save(Dictitem dictitem, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, dictitem)){
			return form(dictitem, model);
		}
		dictitemService.save(dictitem);
		//addMessage(redirectAttributes, "保存字典项管理成功");
		//return "redirect:"+Global.getAdminPath()+"/sys/dictitem/?repage";
		model.addAttribute("dictitem", dictitem);
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("opt","save");
		model.addAttribute("message","保存字典项管理成功");
		return "modules/sys/dict/dictitemForm";
	}
	
	@RequiresPermissions("sys:dictitem:edit")
	@RequestMapping(value = "delete")
	public String delete(Dictitem dictitem, RedirectAttributes redirectAttributes) {
		dictitemService.delete(dictitem);
		addMessage(redirectAttributes, "删除字典项管理成功");
		return "redirect:"+Global.getAdminPath()+"/sys/dictitem/?repage";
	}

	@RequiresPermissions("sys:dictitem:edit")
	@RequestMapping(value = "batchDelete")
	public String delete(String ids, RedirectAttributes redirectAttributes) {
		dictitemService.delete(ids);
		addMessage(redirectAttributes, "删除字典项管理成功");
		return "redirect:"+Global.getAdminPath()+"/sys/dictitem/?repage";
	}
	
	
	@RequiresPermissions("sys:dictitem:view")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String type, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Dictitem dictitem = new Dictitem();
		
		List<Dictitem> list = dictitemService.findList(dictitem );
		for (int i=0; i<list.size(); i++){
			Dictitem e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getCode());
			map.put("pId", e.getDictitem()==null?null:e.getDictitem().getId());
			map.put("name", e.getName());
			mapList.add(map);
		}
		return mapList;
	}
	
	@RequiresPermissions("sys:dictitem:view")
	@RequestMapping(value = "asyncTree")
	public void asyncLoadTreeData(String id,HttpServletRequest request, HttpServletResponse response, Model model) {
		
		Dictitem dt = new Dictitem();
		Dictitem parentDt = new Dictitem();
		parentDt.setId(id);
		dt.setDictitem(parentDt );
		List<Dictitem> dictitems = dictitemService.findList(dt);
		List<TreeVo> treeVoList = new ArrayList<TreeVo>();
		
		if(dictitems!=null&&dictitems.size()>0){
			for (Dictitem dictitem : dictitems) {
				TreeVo treeVo = new TreeVo();
				treeVo.setUk(dictitem.getId());
				treeVo.setId(dictitem.getCode());
				treeVo.setName(dictitem.getName());
				treeVo.setpId(id);
				treeVo.setInfo(dictitem.getRemarks());
				treeVo.setChecked(false);
				
				parentDt.setId(dictitem.getCode());
				dt.setDictitem(parentDt );
				List<Dictitem> children = dictitemService.findList(dt);
				Boolean flag = children.size()>0?true:false;
				
				treeVo.setIsParent(flag);
				treeVo.setHasChild(flag);
				treeVoList.add(treeVo);
			}
		}
		JSONArray jsonArray = JSONArray.fromObject(treeVoList);
		String treeListStr = jsonArray.toString();
		ActionHelp.WriteStrToOut(response, treeListStr);
	}

	/**
	 * 批量修改排序
	 */
	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts,HttpServletRequest request, RedirectAttributes redirectAttributes) {
    	int len = ids.length;
    	Dictitem[] entitys = new Dictitem[len];
    	for (int i = 0; i < len; i++) {
    		entitys[i] = dictitemService.get(ids[i]);
    		entitys[i].setDictsort(sorts[i]);
    		dictitemService.save(entitys[i]);
    	}
    	
    	addMessage(redirectAttributes, "更新顺序成功");
		return "redirect:"+Global.getAdminPath()+"/sys/dictitem/?repage";
	}
	
	@RequiresPermissions("cms:recommen:edit")
	@ResponseBody
	@RequestMapping(value = "ajaxDelete")
	public Map<String, String> ajaxDelete(String ids,HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			dictitemService.delete(ids);
			map.put("message", "删除成功");
			map.put("success", "1");
		} catch (Exception e) {
			// TODO: handle exception
			map.put("message", "删除失败！");
			map.put("success", "0");
			return map;
		}
		return map;
	}
}